﻿#region << 版 本 注 释 >>
/*----------------------------------------------------------------
// Copyright (C) 2022 kingerrobot
// 版权所有。 
//
// 文件名：TaskImpl
// 文件功能描述：
//
// 创建者：名字 (zzl)
// 时间：2022/1/26 16:49:20
//
// 修改人：
// 时间：
// 修改说明：
// 版本：V1.0.0
//----------------------------------------------------------------*/
#endregion


using KingerRobot.MexicoSailunMDC.Dao;
using KingerRobot.MexicoSailunMDC.Spi;
using KingerRobot.MexicoSailunMDC.SpiService.DTO;
using System;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.Security.Cryptography;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace KingerRobot.MexicoSailunMDC.SpiService;

public class TaskImpl : ITaskService
{
    private readonly static ITask _Task = new BTask();
    private readonly static ITaskCmd _TaskCmd = new BTaskCmd();
    private readonly static IRcsLocation _RcsLocation = new BRcsLocation();
    private readonly static IRcsEquipCrn _RcsEquipCrn = new BRcsEquipCrn();
    private readonly static IProdSkuProduct _ProdSkuProduct = new BProdSkuProduct();
    private readonly static IProdProduct _ProdProduct = new BProdProduct();
    private readonly static IProdMaterial _ProdMaterial = new BProdMaterial();
    private readonly static IWcsAsrsCrnInput _WcsAsrsCrnInput = new BWcsAsrsCrnInput();
    private readonly static IWcsAsrsCrnOutPut _WcsAsrsCrnOutput = new BWcsAsrsCrnOutPut();
    private readonly static IWcsNetInCuring _WcsNetInCuring = new BWcsNetInCuring();
    private readonly static IWcsLocSku _WcsLocSku = new BWcsLocSku();
    private readonly static IWmsSetting _WmsSetting = new BWmsSetting();
    private readonly static IRcsEquip _RcsEquip = new BRcsEquip();
    private readonly static IWcsAsrsCrnAbnormalOutPut _WcsAsrsCrnAbnormalOutPut = new BWcsAsrsCrnAbnormalOutPut();
    private readonly static IWcsAsrsCrnAbnormalInput _WcsAsrsCrnAbnormalInput = new BWcsAsrsCrnAbnormalInput();
    private readonly static IExWarehousingAfterService _ExWarehousingAfterService = new ExWarehousingAfterImpl();
    private readonly static IBakTask _BakTask = new BBakTask();
    private readonly static IWarehousingOutService _WarehousingOutService = new WarehousingOutImpl();
    private readonly static IWmsOutOrderMaster _WmsOutOrderMaster = new BWmsOutOrderMaster();
    private readonly static IWcsOutputLog _WcsOutputLog = new BWcsOutputLog();
    private readonly static IWms2MesService _Wms2MesService = new Wms2MesImpl();
    private readonly static IWmsOutOrderSummary _WmsOutOrderSummary = new BWmsOutOrderSummary();
    private readonly static IWcsNetAbnormal _WcsNetAbnormal = new BWcsNetAbnormal();
    private readonly static IProdSku _ProdSku = new BProdSku();
    private readonly static IAbnormal _Abnormal = new BAbnormal();



    public int BakAndDeleteTaskAndCmd(long taskId)
    {
        var task = BakAndDeleteTask(taskId);
        var cmd = _TaskCmd.BakAndDeleteCmd(taskId);

        return task & cmd;
    }

    public int BakAndDeleteCmd(long taskId)
    {
        // 修改状态
        _TaskCmd.UpdateTaskCmdStatus(0, taskId, (int)EnumTaskStatus.Finish);
        // 备份删除 lsq注释
        var result = _TaskCmd.BakAndDeleteCmd(taskId);
        return result;
    }


    public int UpdateTaskIsOutScannerByTaskNo(int taskNo)
    {
        var result = _Task.UpdateTaskIsOutScannerByTaskNo(taskNo);
        return result;
    }
    public List<POWcsTask> GetTasksByGroupNo(int groupNo)
    {
        var result = _Task.GetTasksByGroupNo(groupNo);
        return result;
    }
    public string GetPoductCodeByTaskNo(int taskNo)
    {
        var result = _Task.GetPoductCodeByTaskNo(taskNo);
        return result;
    }
    public List<POWcsTask> GetTasksByGroupNoAndScanner(int groupNo, long scannerLoc)
    {
        var result = _Task.GetTasksByGroupNoAndScanner(groupNo, scannerLoc);
        return result;

    }
    public List<POWcsTaskCmd> GetExecutedTaskCmds()
    {
        var db = Db.Default;

        return db.WcsTaskCmds.Where(f => f.CmdStatus == (int)EnumTaskStatus.Executed).ToList();
    }
    public List<POWcsTaskCmd> GetCmdTestV5()
    {
        var dbHelper = new DbHelper();
        var sql = new StringBuilder();
        List<POWcsTaskCmd> results = new();
        sql.Append(@$"select [objid] as Id
             ,[task_id] as TaskId
             ,[task_no] as TaskNo
             ,[task_type] as TaskType
             ,[equip_id] as EquipId
             ,[start_loc] as StartLoc
             ,[current_loc] as CurrentLoc
             ,[target_loc] as TargetLoc
             ,[cmd_type] as CmdType
             ,[cmd_status] as CmdStatus
             ,[spin_angle] as SpinAngle
             ,[is_spray] as IsSpray
             ,[pair_wait] as PairWait
             ,[finish_loc] as FinishLoc
             ,[finish_mode] as FinishMode
             ,[finish_time] as FinishTime
             ,[create_time] as CreateTime
             ,[update_time] as UpdateTime
             ,[use_flag] as UseFlag
             ,[remark_memo] as RemarkMemo
             ,[execute_time] as ExecuteTime
             from wcs_task_cmd
             where cmd_status = 2");

        dbHelper.CommandText = sql.ToString();
        dbHelper.CommandType = System.Data.CommandType.Text;
        var data = dbHelper.GetXDataTable();
        if (data is not null && data.Rows.Length > 0)
        {

            for (int i = 0; i < data.DataTable.Rows.Count; i++)
            {
                //POWcsTaskCmd result = new();
                //var row = data.DataTable.Rows[i];
                //result.Id = !string.IsNullOrWhiteSpace(row.Value(nameof(result.Id))) ? decimal.ToInt64(Convert.ToDecimal(row.Value(nameof(result.Id)))) : 0;
                //result.TaskId = !string.IsNullOrWhiteSpace(row.Value(nameof(result.TaskId))) ? decimal.ToInt64(Convert.ToDecimal(row.Value(nameof(result.TaskId)))) : 0;
                //result.TaskNo = !string.IsNullOrWhiteSpace(row.Value(nameof(result.TaskNo))) ? Convert.ToInt32(row.Value(nameof(result.TaskNo))) : 0;
                //result.TaskType = !string.IsNullOrWhiteSpace(row.Value(nameof(result.TaskType))) ? Convert.ToInt32(row.Value(nameof(result.TaskType))) : 0;
                //result.EquipId = !string.IsNullOrWhiteSpace(row.Value(nameof(result.EquipId))) ? decimal.ToInt64(Convert.ToDecimal(row.Value(nameof(result.EquipId)))) : 0;
                //result.StartLoc = !string.IsNullOrWhiteSpace(row.Value(nameof(result.StartLoc))) ? decimal.ToInt64(Convert.ToDecimal(row.Value(nameof(result.StartLoc)))) : 0;
                //result.CurrentLoc = !string.IsNullOrWhiteSpace(row.Value(nameof(result.CurrentLoc))) ? decimal.ToInt64(Convert.ToDecimal(row.Value(nameof(result.CurrentLoc)))) : 0;
                //result.TargetLoc = !string.IsNullOrWhiteSpace(row.Value(nameof(result.TargetLoc))) ? decimal.ToInt64(Convert.ToDecimal(row.Value(nameof(result.TargetLoc)))) : 0;
                //result.CmdType = !string.IsNullOrWhiteSpace(row.Value(nameof(result.CmdType))) ? Convert.ToInt32(row.Value(nameof(result.CmdType))) : 0;
                //result.CmdStatus = !string.IsNullOrWhiteSpace(row.Value(nameof(result.CmdStatus))) ? Convert.ToInt32(row.Value(nameof(result.CmdStatus))) : 0;
                //result.SpinAngle = !string.IsNullOrWhiteSpace(row.Value(nameof(result.SpinAngle))) ? Convert.ToDecimal(row.Value(nameof(result.SpinAngle))) : 0;
                //result.IsSpray = !string.IsNullOrWhiteSpace(row.Value(nameof(result.IsSpray))) ? Convert.ToInt32(row.Value(nameof(result.IsSpray))) : 0;
                //result.PairWait = !string.IsNullOrWhiteSpace(row.Value(nameof(result.PairWait))) ? Convert.ToInt32(row.Value(nameof(result.PairWait))) : 0;
                //result.FinishLoc = !string.IsNullOrWhiteSpace(row.Value(nameof(result.FinishLoc))) ? Convert.ToInt64(row.Value(nameof(result.FinishLoc))) : 0;
                //result.FinishMode = !string.IsNullOrWhiteSpace(row.Value(nameof(result.FinishMode))) ? Convert.ToInt32(row.Value(nameof(result.FinishMode))) : 0;
                //result.FinishTime = !string.IsNullOrWhiteSpace(row.Value(nameof(result.FinishTime))) ? Convert.ToDateTime(row.Value(nameof(result.FinishTime))) : null;
                //result.CreateTime = !string.IsNullOrWhiteSpace(row.Value(nameof(result.CreateTime))) ? Convert.ToDateTime(row.Value(nameof(result.CreateTime))) : null;
                //result.UpdateTime = !string.IsNullOrWhiteSpace(row.Value(nameof(result.UpdateTime))) ? Convert.ToDateTime(row.Value(nameof(result.UpdateTime))) : null;
                //result.ExecuteTime = !string.IsNullOrWhiteSpace(row.Value(nameof(result.ExecuteTime))) ? Convert.ToDateTime(row.Value(nameof(result.ExecuteTime))) : null;
                //result.UseFlag = !string.IsNullOrWhiteSpace(row.Value(nameof(result.UseFlag))) ? Convert.ToInt32(row.Value(nameof(result.UseFlag))) : 0;
                //result.RemarkMemo = row.Value(nameof(result.RemarkMemo));
                //results.Add(result);
            }
        }
        return results;
    }


    public POWcsTask GetTaskById(long? taskId)
    {
        var db = Db.Default;

        return db.WcsTasks.Where(f => f.Id == taskId).FirstOrDefault();
    }

    public BizTaskBeanV2 GetTaskByExecuteStartLoc(long StartLoc)
    {
        var result = _Task.GetTaskByExecuteStartLoc(StartLoc);
        return result;
    }
    public BizTaskBeanV2 GetTaskByCmdExecuteStartLoc(long StartLoc)
    {
        var result = _Task.GetTaskByCmdExecuteStartLoc(StartLoc);
        return result;
    }
    public List<BizTaskBeanV2> GetTaskByExecuteStartLocV3(long StartLoc)
    {
        var result = _Task.GetTaskByExecuteStartLocV3(StartLoc);
        return result;
    }
    public BizTaskBeanV2 GetTaskByExecuteStartLocV2(long StartLoc)
    {
        BizTaskBeanV2 result = new();
        var dbHelper = new DbHelper();
        var sql = new StringBuilder();

        sql.Append(@$"SELECT TOP 1 [w].[task_no] as TaskNo, [r0].[plc_code] as TargetCmdPlcLoc , [r].[plc_code] as TargetPlcLoc, [p].[sku_code] as ProductCode,
        COALESCE([p0].[outside_diameter], 0.0) as OutSize ,COALESCE([w].[task_type], 0) as TaskType, [w].[create_time] as CreateTime
        FROM [wcs_task] AS [w]
        INNER JOIN [wcs_task_cmd] AS [w0] ON [w].[objid] = [w0].[task_id]
        INNER JOIN [prod_sku] AS [p] ON [w].[sku_id] = [p].[objid]
        INNER JOIN [prod_material] AS [p0] ON [p].[material_id] = [p0].[objid]
        INNER JOIN [rcs_location] AS [r] ON [w].[target_loc] = [r].[objid]
        INNER JOIN [rcs_location] AS [r0] ON [w0].[target_loc] = [r0].[objid]
        WHERE ((([w].[task_status] < 2) AND ([w].[is_download] = 0)) AND ([w].[start_loc] = {StartLoc})) AND ([w].[task_type] IN (3, 9) OR ([w].[direct_delivery] = 1))
        ORDER BY [w].[create_time]");

        dbHelper.CommandText = sql.ToString();
        dbHelper.CommandType = System.Data.CommandType.Text;
        var data = dbHelper.GetXDataTable();
        if (data is not null && data.Rows.Length > 0)
        {
            //var row = data.DataTable.Rows[0];
            //result.OutSize = !string.IsNullOrWhiteSpace(row.Value(nameof(result.OutSize))) ? decimal.ToInt32(Convert.ToDecimal(row.Value(nameof(result.OutSize)))) : 0;
            //result.TaskNo = !string.IsNullOrWhiteSpace(row.Value(nameof(result.TaskNo))) ? Convert.ToInt32(row.Value(nameof(result.TaskNo))) : 0;
            //result.TargetCmdPlcLoc = row.Value(nameof(result.TargetCmdPlcLoc));
            //result.TargetPlcLoc = row.Value(nameof(result.TargetPlcLoc));
            //result.ProductCode = row.Value(nameof(result.ProductCode));
            //result.CreateTime = !string.IsNullOrWhiteSpace(row.Value(nameof(result.CreateTime))) ? Convert.ToDateTime(row.Value(nameof(result.CreateTime))) : null;
            //result.TaskType = !string.IsNullOrWhiteSpace(row.Value(nameof(result.TaskType))) ? Convert.ToInt32(row.Value(nameof(result.TaskType))) : 0;
        }
        return result;

    }
    public int UpdateTaskDown(int? taskNo, int down)
    {
        var result = _Task.UpdateTaskDown(taskNo ?? 0, down);
        return result;

    }
    /// <summary>
    /// 同步监控页面的堆垛机任务
    /// </summary>
    /// <returns></returns>
    public int SyncScadaCrnTask() 
    {
        var result = _Task.SyncScadaCrnTask();
        return 1;
    }

    public int FinishAbnormOutTask(int taskNo)
    {
        var result = 0;
        var task = _Task.GetTaskByTaskNo(taskNo);
        //var task = _Task.GetExecutedByTaskNo(taskNo);
        if (task is null)
        {
            return result;
        }
        var taskId = task.Id ?? 0;
        //var tireBarcode = _ProdProduct.GetCodeBySkuId(skuId);
        var targetLoc = task.TargetLoc ?? 0;
        var summaryId = task.SummaryId ?? 0;
        var masterId = task.MasterId ?? 0;

        //修改任务状态为完成
        _Task.UpdateTaskAndCmdStatus(targetLoc, taskId, (int)EnumTaskStatus.Finish);
        // 备份删除
        result = _Task.BakAndDeleteTaskAndCmd(taskId);


        // 16.异常输送（WMS->MES）

        // 修改货位标识
        //_RcsLocation.UpdateLocationAndWcsLocWithSkuId(skuId, startLoc, targetLoc, true);


        //删除出库订单
        if (masterId > 0)
        {
            var master = _WmsOutOrderMaster.GetOutOrderMasterById(masterId);
            _WmsOutOrderSummary.BakAndDeleteOutOrderSummary(summaryId);
            var summaryCount = _WmsOutOrderSummary.GetOutOrderSummaryByMasterId(masterId).Count();
            if (summaryCount == 0)
            {
                _WmsOutOrderMaster.BakOutOderMaster(master);
                _WmsOutOrderMaster.DeleteOutOderMaster(master.Id);
            }
        }


        return result;

    }
    public bool IsNeedFinish(POWcsTask task, POWcsTaskCmd cmd)
    {
        var taskGroup = task?.TaskGroup ?? 0;

        if (taskGroup == 0)
        {
            return false;
        }

        var time = DateTime.Now.AddHours(-1);

        var db = Db.Default;

        var bakTaskCmds = db.BakWcsTasks.Join(db.BakWcsTaskCmds, f => f.Id, s => s.TaskId, (f, s) => new
        {
            Task = f,
            Cmd = s
        })
        .Where(f => f.Task.TaskGroup == taskGroup
                    && f.Cmd.FinishTime > time
                    && f.Cmd.CmdType == (int)EnumTaskType.EMS
                    && f.Task.TaskType == (int)EnumTaskType.EMS
                    && f.Cmd.CmdStatus == (int)EnumTaskStatus.Finish).ToList();

        if (bakTaskCmds.Count <= 0)
        {
            return false;
        }

        var bakTaskCmd = bakTaskCmds.FirstOrDefault();

        if (bakTaskCmd is null || bakTaskCmd.Task is null || bakTaskCmd.Cmd is null || cmd is null)
        {
            return false;
        }

        var createTime1 = cmd?.CreateTime ?? DateTime.MaxValue;
        var createTime2 = bakTaskCmd.Cmd.CreateTime ?? DateTime.MinValue;

        var timeSpain = (createTime1 - createTime2).TotalSeconds;

        if (timeSpain > -2 && timeSpain < 2)
        {
            return true;
        }

        return false;

    }
    public int BakTask(long taskId)
    {
        var task = _Task.GetTaskByTaskId(taskId);
        if (task is null)
        {
            return 0;
        }
        var db = Db.Default;

        var result = 0;
        try { result = db.BakWcsTasks.CopyFrom(task); } catch (Exception ex) { WriteLog(ex.ToString()); };
        return result;
    }
    public int DeleteTask(long taskId)
    {
        var db = Db.Default;
        var result = db.WcsTasks
            .Where(t => t.Id == taskId).Delete();

        return result;
    }
    public int BakAndDeleteTask(long taskId)
    {
        var bak = BakTask(taskId);
        var del = DeleteTask(taskId);
        return del & bak;
    }
    public int UpdateTaskCmdStatus(long locId, long taskId, int status)
    {
        return _TaskCmd.UpdateTaskCmdStatus(locId, taskId, status);
    }
    public int UpdateTaskRemark(int taskNo, string remark)
    {
        return _Task.UpdateTaskReamrkByTaskNo(taskNo, remark);
    }

    public TaskStatusBean GetTaskTypeByLocId(long locId)
    {

        var wcsLocSku = _WcsLocSku.GetWcsLocSkuByLocId(locId);
        //WriteLog($"{locId}开始执行查找任务类型210", true);
        if (wcsLocSku is null)
        {
            return new TaskStatusBean();
        }
        //WriteLog($"{locId}开始执行查找任务类型215", true);
        // 获取任务
        var skuId = wcsLocSku.SkuId.GetValueOrDefault();

        var task = _Task.GetTaskBySkuId(skuId);

        if (task is null)
        {

            // 任务不存在 创建异常任务
            //var abnormal = _WcsNetAbnormal.GetWcsNetAbnormalByStartLoc(10030301);
            //if (abnormal is null)
            //{
            //    WriteLog($"-4：线体异常口 {locId},不存在.");
            //    return null;
            //}
            //var ptask = _Task.CreateTask(new()
            //{
            //    StartLoc = locId,
            //    TargetLoc = abnormal.TargetLoc ?? 0,
            //    Type = (int)EnumTaskType.Transportation,
            //    SkuId = skuId,
            //    TaskNo = K8.LSF.Client.CodeValue(new DateTime(), "TaskNo").ToInt(0),
            //    StartEquip = locId,
            //    Status = (int)EnumTaskStatus.Executed,
            //    Remark = $"出库取货位{locId},任务不存在,创建异常口任务",
            //});
            //return new TaskStatusBean(2, ptask?.Id ?? 0);
            return new TaskStatusBean();
        }
        //_WcsOutputLog.CreateOrUpdateWcsOutputLog(task.Id ?? 0, task.TaskNo ?? 0, (int)EnumOutputLogPlan.LineSelectStart);
        //49.176
        //50.157

        // 获取指令
        var taskId = task.Id ?? 0;
        //WriteLog($"{taskId}开始执行查找任务类型229", true);
        var taskCmd = _TaskCmd.GetTaskCmdByTaskId(taskId);
        //WriteLog($"{taskId}开始执行查找任务类型231", true);
        if (taskCmd is not null)
        {
            if (taskCmd.StartLoc == locId
                && taskCmd.CmdStatus == (int)EnumTaskCmdStatus.Executable)
            {
                //WriteLog($"{taskId}开始执行查找任务类型237", true);
                // 重新执行
                return new TaskStatusBean(4, taskId);
            }

            if (taskCmd.TargetLoc == locId)
            {
                // 重新出库完成
                var taskNo = task.TaskNo.GetValueOrDefault();
                var targetLoc = task.TargetLoc.GetValueOrDefault();
                var result = _WarehousingOutService.FinishTask(taskNo, targetLoc);
                if (result > 0)
                {
                    //WriteLog($"{taskId}开始执行查找任务类型243", true);
                    // 1：普通出库；2：异常线体；3：堆垛机异常
                    return new TaskStatusBean(result, taskId);
                }
            }

            return new TaskStatusBean();
        }

        var locTaskId = wcsLocSku.TaskId.GetValueOrDefault();
        if (taskCmd is null && locTaskId == 0)
        {
            if (task.TaskType == (int)EnumTaskType.Warehousing)
            {
                return new TaskStatusBean(2, taskId);
            }
            var masterId = task.MasterId.GetValueOrDefault();
            var master = _WmsOutOrderMaster.GetOutOrderMasterById(masterId);
            if (master is null)
            {
                //WriteLog($"{taskId}开始执行查找任务类型260", true);
                return new TaskStatusBean();
            }

            if (master.OrderType != (int)EnumCodeOutOrderType.WarehouseLocation)
            {
                // WriteLog($"{taskId}开始执行查找任务类型266", true);
                // 普通出库
                //_WcsOutputLog.CreateOrUpdateWcsOutputLog(task.Id ?? 0, task.TaskNo ?? 0, (int)EnumOutputLogPlan.LineSelectEnd);
                return new TaskStatusBean(1, taskId);
            }
            // WriteLog($"{taskId}开始执行查找任务类型270", true);
            // 异常线体
            return new TaskStatusBean(2, taskId);
        }

        return new TaskStatusBean();
    }
    public BizTaskBean GetTaskBeanByTaskNo(int taskNo)
    {
        WriteLog($"任务号{taskNo}开始查找任务", true);
        var task = _Task.GetTaskByTaskNo(taskNo);
        if (task == null)
        {
            WriteLog($"任务号{taskNo} 查找任务isnull", true);
            return null;
        }

        var taskCmd = _TaskCmd.GetTaskCmdByTaskId(task.Id.GetValueOrDefault());
        var loction = _RcsLocation.GetLocationById(task.TargetLoc ?? 0);
        var loctionCmd = _RcsLocation.GetLocationById(taskCmd?.TargetLoc ?? 0);
        var skuId = task.SkuId ?? 0;
        var material = _ProdMaterial.GetMaterialBySkuId(skuId);
        var outSize = decimal.ToInt32(material?.OutsideDiameter ?? 0M);

        var result = new BizTaskBean
        {

            Id = task.Id,
            TaskNo = task.TaskNo,
            SkuId = task.SkuId ?? 0,
            CmdType = taskCmd?.CmdType ?? task.TaskType,
            TargetLoc = taskCmd?.TargetLoc,
            TargetCmdPlcLoc = loctionCmd?.PlcCode,
            TargetPlcLoc = loction?.PlcCode,
            //IsSpray = task.IsSpray,
            //SpinAngle = (taskCmd?.SpinAngle ?? 0) * 10,
            TaskGroup = task.TaskGroup,
            TaskGroupIndex = task.TaskGroupIndex,
            PairWait = taskCmd?.PairWait ?? 0,
            StartLoc = taskCmd?.StartLoc ?? 0,
            Status = taskCmd?.CmdStatus ?? 0,
            // Paint = taskCmd?.IsSpray == 1M ? 10 : 20,
            //OverTurn = !"Up".Equals(material?.Pcspcrbarcodeposition ?? "") ? 0 : 1,
            OutSize = outSize,
        };
        // WriteLog($"任务号{taskNo}查找任务完成,{result.ToJson()}", true);
        return result;
    }


    public BizTaskBean GetTaskBeanByTaskNoV3(int taskNo)
    {
        WriteLog($"任务号{taskNo}开始查找任务a", true);
        var task = _Task.GetTaskByTaskNo(taskNo);
        if (task == null)
        {
            WriteLog($"任务号{taskNo} 查找任务isnull", true);
            return null;
        }

        var taskCmd = _TaskCmd.GetTaskCmdByTaskId(task.Id.GetValueOrDefault());

        var result = new BizTaskBean
        {
            TaskNo = task.TaskNo,
            CmdType = taskCmd?.CmdType ?? task.TaskType,
            TargetLoc = taskCmd?.TargetLoc,
        };
        WriteLog($"任务号{taskNo}完成查找任务a", true);
        return result;
    }

    //_ProdSku.GetProdSkuBySkuCode
    public BizTaskBean GetTaskBeanByTaskId(long taskId)
    {
        var task = _Task.GetTaskByTaskId(taskId);
        if (task == null)
        {
            return null;
        }

        var taskCmd = _TaskCmd.GetTaskCmdByTaskId(task.Id.GetValueOrDefault());

        var loction = _RcsLocation.GetLocationById(task.TargetLoc.GetValueOrDefault());

        var loctionCmd = _RcsLocation.GetLocationById(taskCmd?.TargetLoc ?? 0);

        var skuId = task.SkuId.GetValueOrDefault();
        var material = _ProdMaterial.GetMaterialBySkuId(skuId);
        var outSize = decimal.ToInt32(material?.OutsideDiameter ?? 0M);

        return new BizTaskBean
        {
            Id = task.Id,
            TaskNo = task.TaskNo,
            SkuId = task.SkuId.GetValueOrDefault(),
            CmdType = taskCmd?.CmdType ?? task.TaskType,
            TargetLoc = taskCmd?.TargetLoc,
            TargetCmdPlcLoc = loctionCmd?.PlcCode,
            TargetPlcLoc = loction?.PlcCode,
            //IsSpray = task.IsSpray,
            //SpinAngle = (taskCmd?.SpinAngle ?? 0) * 10,
            TaskGroup = task.TaskGroup,
            TaskGroupIndex = task.TaskGroupIndex,
            PairWait = taskCmd?.PairWait ?? 0,

            StartLoc = taskCmd?.StartLoc ?? 0,
            Status = taskCmd?.CmdStatus ?? 0,

            //Paint = taskCmd?.IsSpray == 1M ? 10 : 20,
            //OverTurn = !"Up".Equals(material?.Pcspcrbarcodeposition ?? "") ? 0 : 1,
            OutSize = outSize,
        };
    }


    public POWcsAsrsCrnOutput GetAsrsCrnOutputByOutPutLocId(long targetLoc)
    {

        var result = _WcsAsrsCrnOutput.GetAsrsCrnOutputByOutPutLocId(targetLoc);
        return result;
    }

    public BizTaskBean GetTaskBeanByProductCode(string productCode)
    {
        var task = _Task.GetTaskByProductCode(productCode);
        if (task == null)
        {
            return null;
        }

        var taskCmd = _TaskCmd.GetTaskCmdByTaskId(task.Id.GetValueOrDefault());

        var loction = _RcsLocation.GetLocationById(task.TargetLoc.GetValueOrDefault());

        var loctionCmd = _RcsLocation.GetLocationById(taskCmd?.TargetLoc ?? 0);

        var skuId = task.SkuId.GetValueOrDefault();
        var material = _ProdMaterial.GetMaterialBySkuId(skuId);
        var outSize = decimal.ToInt32(material?.OutsideDiameter ?? 0M);

        return new BizTaskBean
        {
            Id = task.Id,
            TaskNo = task.TaskNo,
            SkuId = task.SkuId.GetValueOrDefault(),
            CmdType = taskCmd?.CmdType ?? task.TaskType,
            TargetLoc = taskCmd?.TargetLoc,
            TargetCmdPlcLoc = loctionCmd?.PlcCode,
            TargetPlcLoc = loction?.PlcCode,
            //IsSpray = task.IsSpray,
            //SpinAngle = (taskCmd?.SpinAngle ?? 0) * 10,
            TaskGroup = task.TaskGroup,
            TaskGroupIndex = task.TaskGroupIndex,
            PairWait = taskCmd?.PairWait ?? 0,

            StartLoc = taskCmd?.StartLoc ?? 0,
            Status = taskCmd?.CmdStatus ?? 0,

            //Paint = taskCmd?.IsSpray == 1M ? 10 : 20,
            //OverTurn = !"Up".Equals(material?.Pcspcrbarcodeposition ?? "") ? 0 : 1,
            OutSize = outSize,

            Remark = task.RemarkMemo,
        };
    }

    public BizTaskBean GetEmsTaskBeanByTaskNo(int taskNo, long locId = 0)
    {
        BizTaskBean result = null;
        var task = _Task.GetEmsTaskByTaskNo(taskNo);
        if (task is null)
        {
            return result;
            ////var productCode = _Task.GetPoductCodeByTaskNo(taskNo);
            //WriteLog($"任务{taskNo}无任务, 开始生成EMS异常任务", true);
            ////var abnormalSkuId = _ProdProduct.GetSkuIdByCodeEMSAbnormal(productCode);
            ////WriteLog($"任务{taskNo}无任务, 开始生成EMS异常任务,记录异常sku{abnormalSkuId}", true);

            //var abnormalSku = _ProdSku.CreateProdSku(new ProdSkuBean()
            //{
            //    SkuCode = "EMSABNORMAL",
            //    MaterialId = 588276728778982273,
            //    ProductBatch = "",
            //    MdTime = DateTime.Now,
            //});

            //var taskId = _Task.CreateOutAbnormalTask(locId, abnormalSku?.Id ?? 0, "条码无任务,生成EMS异常任务", null, taskNo);
            //WriteLog($"任务{taskNo}无任务, 生成EMS异常任务成功{taskId}", true);
            ////先创建异常任务  再重新查找任务
            //task = _Task.GetTaskByTaskId(taskId);
        }
        try
        {
            var taskCmd = _TaskCmd.GetTaskCmdByTaskId(task.Id ?? 0);

            var loction = _RcsLocation.GetLocationById(task.TargetLoc ?? 0);

            var loctionCmd = _RcsLocation.GetLocationById(taskCmd?.TargetLoc ?? 0);

            var skuId = task.SkuId ?? 0;
            var material = _ProdMaterial.GetMaterialBySkuId(skuId);
            var outSize = decimal.ToInt32(material?.OutsideDiameter ?? 0M);

            result = new BizTaskBean
            {
                Id = task.Id,
                TaskNo = task.TaskNo,
                SkuId = task.SkuId ?? 0,
                CmdType = taskCmd?.CmdType ?? task.TaskType,
                TargetLoc = taskCmd?.TargetLoc,
                TargetCmdPlcLoc = loctionCmd?.PlcCode,
                TargetPlcLoc = loction?.PlcCode,
                //IsSpray = task.IsSpray,
                //SpinAngle = (taskCmd?.SpinAngle ?? 0) * 10,
                TaskGroup = task.TaskGroup,
                TaskGroupIndex = task.TaskGroupIndex,
                PairWait = taskCmd?.PairWait ?? 0,

                StartLoc = taskCmd?.StartLoc ?? 0,
                Status = taskCmd?.CmdStatus ?? 0,

                //Paint = taskCmd?.IsSpray == 1M ? 10 : 20,
                //OverTurn = !"Up".Equals(material?.Pcspcrbarcodeposition ?? "") ? 0 : 1,
                OutSize = outSize,

                Remark = task.RemarkMemo,
            };
        }
        catch (Exception ex)
        {
            WriteLog($"任务{taskNo}, 生成EMS异常{ex.ToString()}", true);
        }
        WriteLog($"任务{taskNo}, taskbean111{result.ToJson()}", true);
        return result;
    }



    public TaskInfo GetTaskByProductCode(string productCode)
    {
        var result = _Task.GetTaskByProductCode(productCode);
        if (result is null)
        {
            return null;
        }
        return new TaskInfo
        {
            Id = result.Id,

            TaskNo = result.TaskNo,
        };
    }
    public TaskInfo GetTaskByExecuteProductCode(string productCode)
    {
        var result = _Task.GetTaskByExecuteProductCode(productCode);
        if (result is null)
        {
            return null;
        }
        return new TaskInfo
        {
            Id = result.Id,

            TaskNo = result.TaskNo,
        };
    }
    public int GetTaskNoByTaskId(long taskId)
    {
        var task = _Task.GetTaskByTaskId(taskId);
        if (task == null)
        {
            return 0;
        }

        return task?.TaskNo ?? 0;
    }
    public string GetTaskByEquipId(long equipId)
    {
        var equip = _RcsEquip.GetWorkEquipById(equipId);
        if (equip is null)
        {
            return $"堆垛机{equipId}已禁用";
        }

        var rcsEquipCrn = _RcsEquipCrn.GetCrnForkById(equipId);
        if (rcsEquipCrn == null)
        {
            return $"堆垛机{equipId}未找到货叉";
        }
        var taskCmd = _TaskCmd.GetExecutedTaskCmdByEquipId(equipId);
        if (taskCmd is not null)
        {
            return $"堆垛机{equipId}有未完成指令ID:{taskCmd.TaskNo},任务流水号:{taskCmd.TaskNo},指令类型:{taskCmd.CmdType}";
        }
        return string.Empty;
    }
    public int CheckOutTaskType(long targerCmdLoc)
    {
        var num = _WcsAsrsCrnAbnormalOutPut.GetAsrsCrnAbnormalOutPutByLocId(targerCmdLoc) is null ? 0 : 1;
        return num;
    }
    public List<BizTaskBean> GetAllExecuteTaskByEquipId(long equipId)
    {
        // 2个 或 4个[中间区域]
        var inputLocs = _WcsAsrsCrnInput.GetWcsAsrsCrnInputsByEquipId(equipId);
        var inLocs = new List<long?>();
        if (inputLocs is not null)
        {
            inLocs.Add(inputLocs.InputLoc1);
            inLocs.Add(inputLocs.InputLoc2);
        }

        // 2个 或 4个[中间区域]
        var outputLocs = _WcsAsrsCrnOutput.GetWcsAsrsCrnOutputALLByEquipId(equipId);
        var outLocs = outputLocs.Select(t => t.OutputLoc1).Concat(outputLocs.Select(t => t.OutputLoc2)).ToList();

        var crns = _RcsEquipCrn.GetCrnForkById(equipId);
        if (crns is null)
        {
            WriteLog($" 未找到堆垛机信息{equipId}，可能不可用 ", true);
            return new List<BizTaskBean>();
        }

        var equipId1 = crns.CrnFork1.GetValueOrDefault();
        var equipId2 = crns.CrnFork2.GetValueOrDefault();

        bool equipFlag = _TaskCmd.IsExecutedTaskCmdByEquipIds(new() { equipId1, equipId2 });

        if (equipFlag)
        {
            WriteLog($" 货叉{equipId1},{equipId2}正在执行任务.", true);
            return new List<BizTaskBean>();
        }

        //var equipFalg1 = _TaskCmd.GetExecutedTaskCmdByEquipId(equipId1);
        //if (equipFalg1 is not null)
        //{
        //    WriteLog($" 货叉正在执行任务{equipFalg1.TaskNo} ", true);
        //    return new List<BizTaskBean>();

        //}

        //var equipFalg2 = _TaskCmd.GetExecutedTaskCmdByEquipId(equipId2);
        //if (equipFalg2 is not null)
        //{
        //    WriteLog($" 货叉正在执行任务{equipFalg2.TaskNo} ", true);
        //    return new List<BizTaskBean>();
        //}


        // 入库可执行任务
        var taskInResult = _TaskCmd.GetIOExecutableWcsTaskCmdsByType(EnumTaskType.Warehousing)
            .Where(x => inLocs.Contains(x.POWcsTaskCmd.StartLoc))
            .Select(t => new BizTaskBean
            {
                Id = t.POWcsTask.Id,
                TaskNo = t.POWcsTask.TaskNo,
                CmdType = t.POWcsTaskCmd.CmdType,
                StartLoc = t.POWcsTaskCmd.StartLoc,
                StartEquip = t.POWcsTaskCmd.EquipId,
                TargetLoc = t.POWcsTaskCmd.TargetLoc,
                TaskGroup = t.POWcsTask.TaskGroup,
                TaskGroupIndex = t.POWcsTask.TaskGroupIndex,
                CreateTime = t.POWcsTaskCmd.CreateTime,
            }).OrderBy(t => t.CreateTime)
            .ToList();

        // 出库可执行任务
        var taskOutResult = _TaskCmd.GetIOExecutableWcsTaskCmdsByType(EnumTaskType.Exwarehouse)
            .Where(x => outLocs.Contains(x.POWcsTaskCmd.TargetLoc))
            .Select(t => new BizTaskBean
            {
                Id = t.POWcsTask.Id,
                CmdType = t.POWcsTaskCmd.CmdType,
                TaskNo = t.POWcsTask.TaskNo,
                StartLoc = t.POWcsTaskCmd.StartLoc,
                StartEquip = t.POWcsTaskCmd.EquipId,
                TargetLoc = t.POWcsTaskCmd.TargetLoc,
                TaskGroup = t.POWcsTask.TaskGroup,
                TaskGroupIndex = t.POWcsTask.TaskGroupIndex,
                CreateTime = t.POWcsTaskCmd.CreateTime,
                CuringTime = (t.POWcsTask.CuringTime ?? 0) - Convert.ToInt32((DateTime.Now - (DateTime)t.POWcsTask.CreateTime).TotalSeconds)


            }).OrderBy(t => t.CuringTime) //任务执行原则(优先硫化时间短的)
            .ToList();

        var count = taskInResult.Count + taskOutResult.Count;

        var taskList = new List<BizTaskBean>();
        foreach (var t in Enumerable.Range(1, count))
        {
            if (crns.NowTaskType == (int)EnumTaskType.Warehousing)
            {
                SetOutputTask(t, taskInResult, taskList, taskOutResult);
            }
            else
            {
                SetInputTask(t, taskInResult, taskList, taskOutResult);
            }
        }
        return taskList.ToList();

    }

    public List<BizTaskBean> GetAllExecuteTaskByEquipIdV2(long equipId)
    {
        // 2个 或 4个[中间区域]
        //var inputLocs = _WcsAsrsCrnInput.GetWcsAsrsCrnInputsByEquipId(equipId);
        //var inLocs = new List<long?>();
        //if (inputLocs is not null)
        //{
        //    inLocs.Add(inputLocs.InputLoc1);
        //    inLocs.Add(inputLocs.InputLoc2);
        //}

        List<long?> equips = new List<long?>() { equipId };
        var inputLocs = _WcsAsrsCrnInput.GetWcsAsrsCrnInputsByEquipIds(equips);
        var inLocs = new List<long?>();
        if (inputLocs is not null)
        {
            foreach (var inputLoc in inputLocs)
            {
                inLocs.Add(inputLoc.InputLoc1);
                inLocs.Add(inputLoc.InputLoc2);
            }
        }


        //inputLocs.Select(t => t.InputLoc1).Concat(inputLocs.Select(t => t.InputLoc2)).ToList();
        // 立库异常口入库执行
        var abnormalInLoc = _WcsAsrsCrnAbnormalInput.GetAsrsCrnAbnormalInPutByCrnId(equipId);
        if (abnormalInLoc is not null)
        {
            inLocs.Add(abnormalInLoc.InputLoc1);
            inLocs.Add(abnormalInLoc.InputLoc2);
        }

        // 2个 或 4个[中间区域]
        var outputLocs = _WcsAsrsCrnOutput.GetWcsAsrsCrnOutputALLByEquipId(equipId);
        var outLocs = outputLocs.Select(t => t.OutputLoc1).Concat(outputLocs.Select(t => t.OutputLoc2)).ToList();

        // 立库异常口出库执行
        var abnormalOutLoc = _WcsAsrsCrnAbnormalOutPut.GetAsrsCrnAbnormalOutPutByCrnId(equipId);
        if (abnormalOutLoc is not null)
        {
            outLocs.Add(abnormalOutLoc.OutputLoc1);
            outLocs.Add(abnormalOutLoc.OutputLoc2);
        }

        var crns = _RcsEquipCrn.GetCrnForkById(equipId);
        if (crns is null)
        {
            WriteLog($" 未找到堆垛机信息{equipId}，可能不可用 ", true);
            return new List<BizTaskBean>();
        }

        var equipId1 = crns.CrnFork1.GetValueOrDefault();
        var equipId2 = crns.CrnFork2.GetValueOrDefault();


        bool equipFlag = _TaskCmd.IsExecutedTaskCmdByEquipIds(new() { equipId1, equipId2 });//5->6 200ms

        if (equipFlag)
        {
            WriteLog($" 货叉{equipId1},{equipId2}正在执行任务.", true);
            return new List<BizTaskBean>();
        }

        //var equipFalg1 = _TaskCmd.GetExecutedTaskCmdByEquipId(equipId1);
        //if (equipFalg1 is not null)
        //{
        //    WriteLog($" 货叉正在执行任务{equipFalg1.TaskNo} ", true);
        //    return new List<BizTaskBean>();
        //}

        //var equipFalg2 = _TaskCmd.GetExecutedTaskCmdByEquipId(equipId2);
        //if (equipFalg2 is not null)
        //{
        //    WriteLog($" 货叉正在执行任务{equipFalg2.TaskNo} ", true);
        //    return new List<BizTaskBean>();
        //}


        // 入库可执行任务
        //.Where(x => inLocs.Contains(x.POWcsTaskCmd.StartLoc))

        var taskIn = _TaskCmd.GetIOExecutableWcsTaskCmdsByType(EnumTaskType.Warehousing);

        //WriteLog($" 入库可执行任务集合{taskIn.Select(t=>t.POWcsTask.TaskNo).ToJson()} ", true);
        var taskInResult = taskIn.Join(inLocs, f => f.POWcsTaskCmd.StartLoc, s => s, (f, s) => f)
        .Select(t => new BizTaskBean
        {
            Id = t.POWcsTask.Id,
            TaskNo = t.POWcsTask.TaskNo,
            CmdType = t.POWcsTaskCmd.CmdType,
            StartLoc = t.POWcsTaskCmd.StartLoc,
            StartEquip = t.POWcsTaskCmd.EquipId,
            TargetLoc = t.POWcsTaskCmd.TargetLoc,
            TaskGroup = t.POWcsTask.TaskGroup,
            TaskGroupIndex = t.POWcsTask.TaskGroupIndex,
            CreateTime = t.POWcsTaskCmd.CreateTime,
        }).OrderBy(t => t.CreateTime)
        .ToList();

        // 出库可执行任务[正常、异常]
        //  .Where(x => outLocs.Contains(x.POWcsTaskCmd.TargetLoc))
        var taskOut = _TaskCmd.GetIOExecutableWcsTaskCmdsByType(EnumTaskType.Exwarehouse);
        //WriteLog($" 出库可执行任务集合{taskOut.Select(t => t.POWcsTask.TaskNo).ToJson()} ", true);
        var taskOutResult = taskOut.Join(outLocs, f => f.POWcsTaskCmd.TargetLoc, s => s, (f, s) =>
        f).Select(t => new BizTaskBean
        {
            Id = t.POWcsTask.Id,
            CmdType = t.POWcsTaskCmd.CmdType,
            TaskNo = t.POWcsTask.TaskNo,
            StartLoc = t.POWcsTaskCmd.StartLoc,
            StartEquip = t.POWcsTaskCmd.EquipId,
            TargetLoc = t.POWcsTaskCmd.TargetLoc,
            TaskGroup = t.POWcsTask.TaskGroup,
            TaskGroupIndex = t.POWcsTask.TaskGroupIndex,
            CreateTime = t.POWcsTaskCmd.CreateTime,
            CuringTime = (t.POWcsTask.CuringTime ?? 0) - Convert.ToInt32((DateTime.Now - (DateTime)t.POWcsTask.CreateTime).TotalSeconds)
        }).OrderBy(t => t.CuringTime) //任务执行原则(优先硫化时间短的)
              .ToList();
        //if (taskOutResult.Count != 0)
        //{
        //    WriteLog($"taskOutResult={taskOutResult.ToJson()}", true);
        //}

        var count = taskInResult.Count + taskOutResult.Count;

        var taskList = new List<BizTaskBean>();
        foreach (var t in Enumerable.Range(1, count))
        {
            if (crns.NowTaskType == (int)EnumTaskType.Warehousing)
            {
                SetOutputTask(t, taskInResult, taskList, taskOutResult);
            }
            else
            {
                SetInputTask(t, taskInResult, taskList, taskOutResult);
            }
        }

        return taskList.ToList();

    }

    public int SetCrnType(long equipId, int type)
    {
        try
        {
            return _RcsEquipCrn.UpdateCrnType(equipId, type);
        }
        catch (Exception ex)
        {

            WriteLog($" 执行异常：{ex.Message} ", true);
            return 0;
        }
    }

    public void SetInputTask(int t, List<BizTaskBean> taskInResult, List<BizTaskBean> taskList, List<BizTaskBean> taskOutResult)
    {
        if (t % 2 == 1 && taskInResult.Count > 0)
        {
            // 入
            SetInTask(taskInResult, taskList);
        }
        else
        {
            SetOutTask(taskOutResult, taskList);
        }

        if (t % 2 == 0 && taskOutResult.Count > 0)
        {
            // 出
            SetOutTask(taskOutResult, taskList);
        }
        else
        {
            SetInTask(taskInResult, taskList);
        }
    }
    public void SetOutputTask(int t, List<BizTaskBean> taskInResult, List<BizTaskBean> taskList, List<BizTaskBean> taskOutResult)
    {
        if (t % 2 == 1 && taskOutResult.Count > 0)
        {
            SetOutTask(taskOutResult, taskList);
        }
        else
        {
            // 入
            SetInTask(taskInResult, taskList);
        }

        if (t % 2 == 0 && taskInResult.Count > 0)
        {
            SetInTask(taskInResult, taskList);
        }
        else
        {
            // 出
            SetOutTask(taskOutResult, taskList);
        }
    }

    private void SetInTask(List<BizTaskBean> taskInResult, List<BizTaskBean> taskList)
    {
        var task = taskInResult.FirstOrDefault();
        if (task is not null)
        {
            taskList.Add(task);
            taskInResult.Remove(task);
        }
    }
    private void SetOutTask(List<BizTaskBean> taskOutResult, List<BizTaskBean> taskList)
    {
        var task = taskOutResult.FirstOrDefault();
        if (task is not null)
        {
            taskList.Add(task);
            taskOutResult.Remove(task);
        }
    }

    public List<TaskInfo> GetAllInTasks()
    {
        var result = _Task.GetIOExecutableWcsTasksByType(EnumTaskType.Warehousing);

        return result.Select(t => new TaskInfo
        {
            Id = t.Id,
            TaskNo = t.TaskNo,
        }).ToList();
    }
    public List<TaskInfo> GetAllOutTasks()
    {
        var result = _Task.GetIOExecutableWcsTasksByType(EnumTaskType.Exwarehouse);

        return result.Select(t => new TaskInfo
        {
            Id = t.Id,

            TaskNo = t.TaskNo,
        }).ToList();
    }
    public int BakAndDeleteCmdByTaskId(long taskId)
    {
        return _TaskCmd.BakAndDeleteCmd(taskId);
    }
    public int IsSprayByTaskNo(int taskNo)
    {
        var result = _TaskCmd.IsSprayByTaskNo(taskNo);
        return result;
    }

    public BizTaskBean GetTaskBeanByExecuteProductCode(string productCode)
    {
        var result = GetTaskByProductCodeV2(productCode);
        return result;

    }
    public BizTaskBean GetTaskBeanByExecuteStartLoc(long startLoc)
    {
        var result = _Task.GetTaskBeanByStartLoc(startLoc);
        return result;
    }

    public BizTaskBean GetTaskByProductCodeV2(string productCode)
    {
        //WriteLog($"下传位条码,开始750", true);
        var result = _Task.GetTaskBeanByProductCode(productCode);
        //WriteLog($"下传位条码,开始751", true);
        return result;
    }

    public BizTaskBean GetTaskByTaskId(long taskId)
    {
        var task = _Task.GetTaskByTaskId(taskId);
        if (task == null)
        {
            return null;
        }

        var taskCmd = _TaskCmd.GetTaskCmdByTaskId(task.Id.GetValueOrDefault());
        var loction = _RcsLocation.GetLocationById(task.TargetLoc.GetValueOrDefault());
        var loctionCmdStart = _RcsLocation.GetLocationById(taskCmd.StartLoc.GetValueOrDefault());
        var loctionCmd = _RcsLocation.GetLocationById(taskCmd.TargetLoc.GetValueOrDefault());
        var skuId = task.SkuId.GetValueOrDefault();
        var productCode = _ProdProduct.GetCodeBySkuId(skuId);
        var material = _ProdMaterial.GetMaterialBySkuId(skuId);
        var outSize = decimal.ToInt32(material?.OutsideDiameter ?? 0M);
        //var height = decimal.ToInt32(material?.MaterialHeight ?? 0M);
        var result = new BizTaskBean()
        {
            Id = task.Id,
            TaskNo = task.TaskNo,
            StartLoc = task.StartLoc,
            StartCmdPlcLoc = loctionCmdStart?.PlcCode,
            TargetLoc = taskCmd?.TargetLoc,
            TargetPlcLoc = loction?.PlcCode,
            TargetCmdPlcLoc = loctionCmd?.PlcCode,
            CmdStatus = taskCmd.CmdStatus.GetValueOrDefault(),
            TaskGroup = task.TaskGroup,
            TaskGroupIndex = task.TaskGroupIndex,
            ProductCode = productCode,
            SkuId = skuId,
            OutSize = outSize,
            //Height = height,
            TaskType = task.TaskType,
        };
        return result;
    }

    public List<BizTaskBean> GetAllInExecuteTaskByEquipId(long equipId)
    {

        var inputLocs = _WcsAsrsCrnInput.GetWcsAsrsCrnInputs().Where(x => x.CrnId == equipId).FirstOrDefault();
        if (inputLocs == null)
        {
            return null;
        }

        var result = _Task.GetIOExecutableWcsTasksByType(EnumTaskType.Warehousing).Where(x => x.StartLoc == inputLocs.InputLoc1 || x.StartLoc == inputLocs.InputLoc2).ToList();
        return result.Select(t => new BizTaskBean
        {
            Id = t.Id,
            TaskNo = t.TaskNo,
            StartLoc = t.StartLoc,
            TargetLoc = t.TargetLoc,
            TaskGroup = t.TaskGroup,
            TaskGroupIndex = t.TaskGroupIndex,
            CreateTime = t.CreateTime,
        }).ToList();
    }
    public List<BizTaskBean> GetAllInExecutedTaskByEquipId(long equipId)
    {

        var inputLocs = _WcsAsrsCrnInput.GetWcsAsrsCrnInputs().Where(x => x.CrnId == equipId).FirstOrDefault();
        if (inputLocs == null)
        {
            return null;
        }

        var result = _Task.GetTaskByType((int)EnumTaskType.Warehousing).Where(x => x.StartLoc == inputLocs.InputLoc1 || x.StartLoc == inputLocs.InputLoc2).ToList();
        return result.Select(t => new BizTaskBean
        {
            Id = t.Id,
            TaskNo = t.TaskNo,
            StartLoc = t.StartLoc,
            TargetLoc = t.TargetLoc,
            TaskGroup = t.TaskGroup,
            TaskGroupIndex = t.TaskGroupIndex,
            CreateTime = t.CreateTime,
        }).ToList();
    }

    public long GetCmdStartLocByTaskNo(int taskNo)
    {

        var taskCmd = _TaskCmd.GetTaskCmdByTaskNo(taskNo);
        if (taskCmd is null)
        {
            return 0;
        }

        return taskCmd.StartLoc ?? 0;
    }

    public int GetTaskTypeByTaskNo(int taskNo)
    {
        var task = _Task.GetTaskByTaskNo(taskNo);
        if (task == null)
        {
            return 0;
        }

        return task?.TaskType ?? 0;
    }

    public BizEmsTask GetTaskCmdByEmsId(long emsId)
    {
        var taskCmds = _TaskCmd.GetTaskCmdByEquipId(emsId);
        if (taskCmds is null)
        {
            return null;
        }
        return new()
        {
            CmdId = taskCmds.Id.GetValueOrDefault(),
            TaskNo = taskCmds.TaskNo.GetValueOrDefault(),
            IsExecuted = taskCmds.CmdStatus != (int)EnumTaskCmdStatus.Executable,
            PairWait = taskCmds.PairWait.GetValueOrDefault(),
        };

    }


    private BizTaskCmdXZBean GetTaskInfo(long taskCmdId)
    {
        var taskCmd = _TaskCmd.GetTaskCmdById(taskCmdId);
        if (taskCmd == null)
        {
            return null;
        }
        var taskId = taskCmd.TaskId.GetValueOrDefault();
        var task = _Task.GetTaskByTaskId(taskId);


        var startLoc = taskCmd.StartLoc ?? 0;
        var targetLoc = taskCmd.TargetLoc ?? 0;
        var skuId = task.SkuId ?? 0;

       // var height = 0;// _ProdProduct.GetProductBindingInfoBySkuId(skuId)?.POProdProduct.Height ?? 0;//获取胎高
        var materialInfo= _ProdMaterial.GetMaterialBySkuId(skuId);
        if (materialInfo==null)
        {
            WriteLog($"未获取到物料信息！skuId:{skuId}", true);
            return null;
        }
        if (materialInfo.MaterialHeight == null)
        {
            WriteLog($"未获取到物料信息！materialInfo:{materialInfo.ToJson()}", true);
            return null;
        }

        //var locs = _RcsLocation.GetLocationsByLocIds(new() { startLoc, targetLoc });

        var startXZ = _RcsLocation.GetLocationById(startLoc);


        var targetXZ = _RcsLocation.GetLocationById(targetLoc);


        //var skuPro = _ProdSkuProduct.GetProdSkuProductBySkuId(skuId);
        //var materialId = skuPro?.MaterialId ?? 0;
        //var material = _ProdMaterial.GetMaterialById(materialId);

        var material = _ProdMaterial.GetMaterialBySkuId(skuId);

        var pairWait = taskCmd.PairWait.GetValueOrDefault();

        // (次)喷涂比例，达到指定数喷涂一次
        var wmsSetting = _WmsSetting.GetWmsSettingByCode(ConstFields.EmsHeight);
        _ = decimal.TryParse(wmsSetting?.Value, out var number);
        decimal start = 1154L;
        decimal target = 3672L;


        var data= new BizTaskCmdXZBean()
        {
            EmsId = taskCmd.EquipId.GetValueOrDefault(),

            TaskNo = task?.TaskNo ?? 0,

            StartX = startXZ?.AxisX ?? 0,
            StartZ = (decimal)(start - (number * materialInfo.MaterialHeight)), //OLDTODO 设置 Ems 小车取胎系数  20250724
            SubSize = material?.InsideDiameter ?? 0,

            TargetX = targetXZ?.AxisX ?? 0,
            TargetZ = (decimal)(target - (number * materialInfo.MaterialHeight)), //OLDTODO 设置 Ems 小车放胎系数 20250724

            StartLoc = taskCmd.StartLoc ?? 0,
            TargetLoc = taskCmd.TargetLoc ?? 0,

            PairWait = pairWait,

            IsAbnormal = task?.TaskType == (int)EnumTaskType.Abnormal,
            CreateTime = taskCmd.CreateTime,
            CmdType = taskCmd?.CmdType,

        };

        WriteLog(data.ToJson(),true);
        return data;
    }

    public BizTaskCmdXZ GetTaskCmdXZ(long taskCmdId, long emsId)
    {
        var bean = GetTaskInfo(taskCmdId);
        if (bean is null)
        {
            return null;
        }
        // WriteLog($"物料信息=== {bean?.ToJson()}");


        //BizTaskCmdXZBean bean2 = null;
        //if (bean.PairWait == 1)
        //{

        //    var startLoc = _WcsNetInCuring.GetWcsNetinCuringByPickupId(emsId)?.TranLoc;
        //    // 配对查找另一条任务信息
        //    var nextTaskCmd = _TaskCmd.GetNextTaskCmdByPairWait(startLoc.GetValueOrDefault(), (int)EnumWait.COMPLETE);


        //    if (nextTaskCmd is null)
        //    {
        //        bean.PairWait = 0;
        //    }
        //    else
        //    {
        //        bean2 = GetTaskInfo(nextTaskCmd.Id.GetValueOrDefault());
        //        if (bean2 is null)
        //        {
        //            bean.PairWait = 0;
        //        }
        //    }
        //}
        BizTaskCmdXZ result = new()
        {

            EmsId = bean?.EmsId ?? 0,

            TaskNo = bean?.TaskNo ?? 0,

            StartX = Convert.ToInt32(Convert.ToDouble(bean?.StartX ?? 0)),

            StartZ = Convert.ToInt32(Convert.ToDouble(bean?.StartZ ?? 0)),



            SubSize = Convert.ToInt32(Convert.ToDouble(bean?.SubSize ?? 0)),

            TargetX = Convert.ToInt32(Convert.ToDouble(bean?.TargetX ?? 0)),

            TargetZ = Convert.ToInt32(Convert.ToDouble(bean?.TargetZ ?? 0)),

            StartLoc = bean?.StartLoc ?? 0,
            TargetLoc = bean?.TargetLoc ?? 0,

            PairWait = bean.PairWait,

            IsAbnormal = bean.IsAbnormal,
            CreateTime = bean.CreateTime,
            CmdType = bean.CmdType,

            //EmsIdB = bean2?.EmsId ?? 0,
            //TaskNoB = bean2?.TaskNo ?? 0,

            //StartBX = Convert.ToInt32(Convert.ToDouble(bean2?.StartX ?? 0)),
            //StartBZ = Convert.ToInt32(Convert.ToDouble(bean2?.StartZ ?? 0)),
            //SubSizeB = Convert.ToInt32(Convert.ToDouble(bean2?.SubSize ?? 0)),

            //TargetBX = Convert.ToInt32(Convert.ToDouble(bean2?.TargetX ?? 0)),
            //TargetBZ = Convert.ToInt32(Convert.ToDouble(bean2?.TargetZ ?? 0)),

            //StartLocB = Convert.ToInt32(Convert.ToDouble(bean2?.StartLoc ?? 0)),
            //TargetLocB = Convert.ToInt32(Convert.ToDouble(bean2?.TargetLoc ?? 0)),

        };

        return result;
    }


    /// <summary>
    /// 出库线体任务创建
    /// </summary>
    public BizTaskBean GetTaskByLocId(long locId)
    {
        // 创建任务
        var locSku = _WcsLocSku.GetWcsLocSkuByLocId(locId);

        if (locSku is null)
        {
            return null;
        }

        var skuId = locSku.SkuId.GetValueOrDefault();
        var task = _Task.GetTaskBySkuId(skuId);
        if (task is null)
        {
            return null;
        }

        var taskId = task.Id.GetValueOrDefault();
        var taskCmd = _TaskCmd.GetTaskCmdByTaskId(taskId);
        if (taskCmd is null)
        {
            long resultTask = 0L;

            if (task.TaskType == (int)EnumTaskType.Exwarehouse)
            {
                // 创建出库指令【目的为了防范服务重启，指令只删除，没有创建，导致异常】
                resultTask = _ExWarehousingAfterService.CreateLocOutTask(locId, taskId);
            }
            if (resultTask <= 0)
            {
                return null;
            }
        }

        if (taskCmd.StartLoc == locId
            && taskCmd.CmdType == (int)EnumTaskType.Transportation
            && taskCmd.CmdStatus == (int)EnumTaskCmdStatus.Executable)
        {
            // 获取任务信息
            var result = GetTaskByTaskId(taskId);
            if (result is not null)
            {
                return result;
            }
        }
        return null;
    }

    public bool GetTaskByStartLocAndCod(long startLoc, int taskNo)
    {
        var taskCmd = _TaskCmd.GetTaskCmdByStartLocAndCode(startLoc, taskNo);
        if (taskCmd is not null)
        {
            return true;
        }
        return false;
    }

    public int DeleteBakTask()
    {
        var wmsSetting = _WmsSetting.GetWmsSettingByCode(ConstFields.DeleteBakTask);
        int.TryParse(wmsSetting?.Value, out int days);
        if (days <= 0)
        {
            return 0;
        }

        var dateTime = DateTime.Now.AddDays(-days);
        var result = _BakTask.DeleteBakTaskByDateTime(dateTime);

        return result;
    }

    public int BakAndDeleteOutAbnormalTaskAndCmdByTaskNo(int taskNo)
    {
        var result = 0;
        var task = _Task.GetTaskByTaskNo(taskNo);
        if (task is not null && task.TaskType == (int)EnumTaskType.Abnormal)
        {
            result = _Task.BakAndDeleteTaskAndCmd(task.Id.GetValueOrDefault());
        }
        return result;
    }

    public int UpdateOutCmdStatus()
    {
        WriteLog("开始执行wcs定时更新指令状态", true);
        try
        {
            var result = _TaskCmd.UpdateOutCmdStatus();
            WriteLog($"结束执行wcs定时更新指令状态,{result}", true);
            return result;
        }
        catch (Exception ex)
        {
            WriteLog($"异常结束执行wcs定时更新指令状态,{ex.ToString()}", true);
            return 0;
        }
    }

    public void UpdateHeight(string materialCode, string height)
    {
        _ProdMaterial.UpdateMaterialHeightByCode(materialCode, height);
    }

    public int DeleteOrCompleteHandTask()
    {
        
        return _Task.DeleteOrCompleteHandTask();
    }
    //private long SetAbnormal(long locId, long equipId, POWcsTask task, string reamrk)
    //{
    //    // 获取异常执行货叉
    //    //var netAbnormal = _WcsNetAbnormal.GetWcsNetAbnormalByStartLoc(locId);
    //    //var ems1 = netAbnormal?.Ems1 ?? 0;
    //    //var ems2 = netAbnormal?.Ems2 ?? 0;
    //    //var equipId = ems1;
    //    //if (_RcsEquip.GetWorkEquipById(ems1) is null)
    //    //{
    //    //    if (_RcsEquip.GetWorkEquipById(ems2) is not null)
    //    //    {
    //    //        equipId = ems2;
    //    //    }
    //    //    else
    //    //    {

    //    //        ////WriteLog($"两个小车{ems1},{ems2} 都不可用.");
    //    //        return 0;
    //    //    }
    //    //}

    //    var skuId = task?.SkuId ?? 0L;
    //    var taskId = task?.Id ?? 0L;
    //    var masterId = task?.MasterId ?? 0L;
    //    var summaryId = task?.SummaryId ?? 0L;
    //    var type = task?.TaskType ?? 0;

    //    // 无法送到进入异常口（结束当前任务、创建异常口任务）
    //    var abnormalTaskCmdId = _Abnormal.LocationAbnormalTaskAndCmdRetCmdId(locId, skuId, reamrk, equipId);
    //    if (abnormalTaskCmdId > 0)
    //    {
    //        // 备份删除
    //        _Task.BakAndDeleteTaskAndCmd(taskId);

    //        var taskCmd = _TaskCmd.GetTaskCmdById(abnormalTaskCmdId);

    //        var newId = taskCmd?.TaskId ?? 0;
    //        var startLoc = taskCmd?.StartLoc ?? 0;
    //        var targetLoc = taskCmd?.TargetLoc ?? 0;

    //        _Task.UpdateTaskOrder(newId, masterId, summaryId);

    //        if (type != (int)EnumTaskType.Abnormal)
    //        {
    //            // 重新请料
    //            _WmsOutOrderSummary.UpdateOutOrderSumaryRealNum(summaryId);

    //            // 异常同步MES
    //            //var productCode = _ProdProduct.GetCodeBySkuId(skuId);

    //            // SyncMes(productCode, startLoc, targetLoc);
    //        }
    //        _WcsLocSku.UpdateWcsLocSkuTask(skuId, abnormalTaskCmdId);
    //        return abnormalTaskCmdId;
    //    }

    //    return abnormalTaskCmdId;
    //}
}